/***************************************************************************
 *   This file is part of KTagger                                          *
 *   Copyright (C) 2010 by Luca Bellonda                                   *
 *   some parts Copyright (C) 2007 Ivan Kukic <ivan.cukic(at)kde.org>      *
 *   lbellonda _at_ gmail.com                                              *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/

#include "Utility.h"
#include "config-ktagger.h"
#include <QtGui>
#include <KStandardDirs>
#include <KLocale>
#include <KMessageBox>

Utility::Utility()
{
}

void Utility::error(const QString & message)
{
    Utility::error(NULL, message) ;
}

void Utility::error(QWidget *parent, const QString & message)
{
    KMessageBox::error(parent, message, APP_TITLE);
}

void Utility::message(const QString & message)
{
    Utility::message(NULL, message);
}

void Utility::message(QWidget *parent, const QString & message)
{
    KMessageBox::information(parent, message, APP_TITLE) ;
}

void Utility::errorNoSel(QWidget *parent)
{
    error(parent, i18n("No item selected"));
}

void Utility::errorOutOfMem(QWidget *parent)
{
    error(parent, i18n("Not enough memory to complete the operation"));
}

void Utility::errorReadingUserSettings()
{
    error(NULL, i18n("error reading user settings"));
}

void Utility::errorSavingUserSettings()
{
    error(NULL, i18n("error saving user settings"));
}

bool Utility::askYN(QWidget *parent, const QString & message)
{
    int result = KMessageBox::questionYesNo(parent, message, APP_TITLE);
    if (result == KMessageBox::Yes) {
        return true;
    }
    return false;
}

void Utility::showWaitCursor()
{
#ifndef QT_NO_CURSOR
    QApplication::setOverrideCursor(Qt::WaitCursor);
#endif
}

void Utility::restoreCursor()
{
#ifndef QT_NO_CURSOR
    QApplication::restoreOverrideCursor();
#endif
}


void Utility::selectComboValue(QComboBox *combo, const int value)
{
    int items = combo->count();
    for (int itemIndex = 0 ; itemIndex < items ; itemIndex++) {
        if (combo->itemData(itemIndex).toInt() == value) {
            combo->setCurrentIndex(itemIndex);
            return;
        }
    }
}

bool Utility::decodeBoolean(const QString &str)
{
    bool isOk ;
    if (0 == str.compare("false", Qt::CaseInsensitive)) {
        return false;
    }
    if (0 == str.compare("true", Qt::CaseInsensitive)) {
        return true;
    }
    int val = str.toInt(&isOk, 10);
    if (!isOk) {
        return false;
    }
    if (val != 0) {
        return true;
    }
    return false;
}

int Utility::decodeInt(const QString &str, const int defaultVale)
{
    bool isOk ;
    int val = str.toInt(&isOk, 10);
    if (!isOk) {
        return defaultVale ;
    }
    return val ;
}

//-------------------------------------------------------

QString Utility::fromBase64(const QString &text)
{
    QByteArray array(text.toAscii());
    QByteArray array2 = QByteArray::fromBase64(array);
    QString strText = array2.data();
    return strText;
}

QString Utility::toBase64(const QString &text)
{
    QByteArray array(text.toAscii());
    QByteArray converted = array.toBase64();
    QString strBase64 = converted.data();
    return strBase64 ;
}

//---------------------------------------------------------------

QString Utility::getLocalDataDir(const QString &dataDirName)
{
    /* this code from Lancelot by Ivan Cukic */
    QDir dir;
    QString path = KStandardDirs::locateLocal("data", KTAGGER_STDDIR, true);
    if (!path.endsWith('/')) {
        path += '/';
    }
    path += dataDirName;
    path += "/";
    dir.setPath(path);
    if (!dir.exists()) {
        if (!dir.mkpath(path)) {
            error(i18n("Impossible to create data directory."));
            return NULL ;
        }
    }
    return dir.absolutePath();
}

//------------------

void Utility::addTagToSet(QTableWidget *table, const QString &tag)
{
    bool isNullFound = false;
    int rowOfInsertion = 0 ;
    int colOfInsertion = 0 ;
    int rows = table->rowCount();
    int columns = table->columnCount();
    for (int row = 0 ; row < rows ; row ++) {
        for (int col = 0 ; col < columns ; col++) {
            QTableWidgetItem *item = table->item(row, col);
            if (NULL != item) {
                QString value = item->text() ;
                if (value == tag) {
                    item->setCheckState(Qt::Checked);
                    return ;
                }
            } else {
                isNullFound = true ;
                rowOfInsertion = row;
                colOfInsertion = col ;
                break;
            }
        }
        if (isNullFound) {
            break;
        }
    }

    if (!isNullFound) {
        // let's add them
        rowOfInsertion = table->rowCount();
        table->setRowCount(rowOfInsertion + 1);
        colOfInsertion = 0 ;
    }
    QTableWidgetItem *itemTag = new QTableWidgetItem(tag);
    itemTag->setCheckState(Qt::Checked);
    itemTag->setFlags(itemTag->flags() & (~Qt::ItemIsEditable));
    table->setItem(rowOfInsertion, colOfInsertion, itemTag);
}


void Utility::getTableSet(QTableWidget *table, QStringList &tags)
{
    int rows = table->rowCount();
    int columns = table->columnCount();
    for (int row = 0 ; row < rows ; row ++) {
        for (int col = 0 ; col < columns ; col++) {
            QTableWidgetItem *item = table->item(row, col);
            if (NULL != item) {
                if (item->checkState() == Qt::Checked) {
                    tags.append(item->text());
                }
            }
        }
    }
}


void Utility::getListSet(QListWidget *list, QStringList &tags)
{
    int rows = list->count();
    for (int row = 0 ; row < rows ; row ++) {
        QListWidgetItem *item = list->item(row);
        if (NULL != item) {
            tags.append(item->text());
        }
    }
}

QStringList Utility::normalizeTags(const QStringList &inputTags)
{
    QStringList newList;
    foreach(QString tag, inputTags) {
        newList.append(tag.toLower());
    }
    return newList;
}
